//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop

#include "Globals.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TdecmpForm *decmpForm;
//---------------------------------------------------------------------------
__fastcall TdecmpForm::TdecmpForm(TComponent* Owner)
 : TForm(Owner)
{
}

//------------------------//
//                        //
//------------------------//
void __fastcall TdecmpForm::cmListDblClick(TObject *Sender)
{
  FILE *rf;
  FILE *tf;
  BYTE *lpRam;
  LONG offset,
       lpPosi,
       size;
  LONG posi;
  long valu;
  long count;
  char buf[260];

  if ( !rom ) return;

  lpRam = ( BYTE *)malloc( 0x20000 );
  if ( !lpRam ){
    ShowMessage( "Error: Out of Memory" );
    return;
  }
  //
  memcpy( lpRam, ram, 0x20000 );
  //---------------------------------
  for ( int i = 0; i < cmList->Items->Count; i++ )
  { //
    if ( cmList->Selected[ i ] )
    {
      sscanf( cmList->Items->Strings[ i ].c_str( ), "%s %X", &buf, &offset );
      //
      lpPosi = Snes2Pc( offset );
      valu   = WGET( rom, lpPosi );
      count  = (valu & 0xFF) >> 1;
      //
      sprintf( buf, "%s/%08X/", cur_dir, offset );
      mkdir( buf );
      //
      sprintf( buf, "%s/%08X/%08X.txt", cur_dir, offset, offset );
      tf = fopen( buf, "wt" );
      if ( !tf ){
        fclose( tf );
        ShowMessage( "Error: Could notcreate 'DATA File'." );
        return;
      }

      valu = -1;
      while( ++valu < count )
      { //
        posi = (offset & 0xFF0000) | (WGET( rom, lpPosi + (valu << 1)) );
        //
        posi = myForm->Decompress( posi );
        size = *(WORD *)&ram[0x11000];
        //
        sprintf( buf, "%s/%08X/%08X.raw", cur_dir, offset, (offset & 0xFF0000) | (WGET( rom, lpPosi + (valu << 1))) );
        rf = fopen( buf, "wb" );
        if ( rf ){
          fwrite( &ram[0xA000], 1, size, rf );
          fclose( rf );
        }
        //
        fprintf( tf, ".COMP %s %08X %08X\n", buf, Snes2Pc((offset & 0xFF0000) | (WGET( rom, lpPosi + (valu << 1)) )), posi );
      }

      //
      memcpy( ram, lpRam, 0x20000 );
      _free( lpRam );
      //
//      cmForm->Close( );
      //
      if ( tf ) fclose( tf );
      ShowMessage( "All data files were decompressed!" );
    } // END IF
  }
}


